<template>
  <div class="app-container">
    <!-- 检索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="算法:" prop="skuName">
        <el-input v-model="queryParams.skuName" placeholder="算法名称" clearable />
      </el-form-item>
      <el-form-item label="特征库层:" prop="layer" label-width="100px">
        <el-select clearable="" v-model="queryParams.layer" filterable placeholder="请选择">
          <el-option v-for="item in layerList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryByForm">检索</el-button>
      </el-form-item>
    </el-form>
    <!-- 新增按钮 -->
    <el-row>
      <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd"
        style="margin-right: 20px">新增算法</el-button>
      <el-button size="small" type="danger" icon="el-icon-delete" @click="handleBatchDel"
        style="margin-right: 20px">批量删除算法</el-button>
      <el-button size="small" type="primary" icon="el-icon-plus" @click="getThreshold"
        style="margin-right: 20px">阈值设置</el-button>
      <el-button size="small" type="warning" icon="el-icon-refresh-right" @click="PTRestartV4"
        style="margin-right: 20px">重启算法服务</el-button>
      <el-button size="small" type="primary" icon="el-icon-search" @click="getRestartResult"
        style="margin-right: 20px">查看重启结果</el-button>
      <!-- <el-button size="small" type="warning" icon="el-icon-refresh-right" @click="syncV4"
        style="margin-right: 20px">算法同步</el-button>
      <el-button size="small" type="primary" icon="el-icon-search" @click="syncResult"
        style="margin-right: 20px">查看同步结果</el-button> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getAlgoData"></right-toolbar>
    </el-row>
    <!-- 表格数据展示 -->
    <el-table :key="changeMark" v-loading="loading" :data="alogData" style="width: 100%;margin-top: 1%;" empty-text="--"
      @selection-change="handleSelectionChange" :default-sort = "{prop: 'id', order: 'descending'}">
      <el-table-column type="selection" width="55" />
      <el-table-column sortable label="算法Id" align="center" prop="id" />
      <el-table-column label="算法名称" align="center" prop="name" />
      <el-table-column label="特征库层" align="center" prop="layer">
        <template slot-scope="scope">
          <div>{{ scope.row.layer === 1 ? '顶层' : scope.row.layer === 2 ? '中间层' : '底层' }}</div>

          <!-- {{  scope.row.layer == "1" ? '顶层' : '中层'}} -->
          <!-- {{scope.row.layer === 1 ? '顶层' :  scope.row.layer === 2 ? '中间层' ? '底层' }}  -->
        </template>
      </el-table-column>
      <el-table-column label="主图" align="center" prop="packageUrl">
        <template slot-scope="scope">
          <div>
            <el-popover trigger="hover" placement="bottom" width="400">
              <img slot="reference" :src="scope.row.packageUrl" style="width: 20px;height: 20px;"
                v-if="scope.row.packageUrl" />
              <img :src="scope.row.packageUrl" style="width: 300px" v-if="scope.row.packageUrl" />
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="当前小图情况" align="center" prop="imageCount">
        <template slot-scope="scope">
          <el-button size="mini" style="font-size: 22px;" type="text" @mouseover.native="(e) => handleEnter(scope.row, e)"
            @mouseout.native="handleOut" @click="handleEdit(scope.row)">
            {{ scope.row.imageCount }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" :disabled="false" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="alogPagn.total > 0" :total="alogPagn.total" :page.sync="alogPagn.pageNum"
      :limit.sync="alogPagn.pageSize" @pagination="aloGpagination" />
    <!-- 新增算法、点击图片数量弹出框 -->
    <el-dialog :title="dialogTitle" v-loading="uploadLoading" element-loading-text="图片上传中"
      element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :visible.sync="dialogOpen"
      :close-on-click-modal="false" :fullscreen="dialogFull" @close="cancel" width="800px" append-to-body>
      <el-form ref="algoForm" :model="algoForm" :rules="algoFormRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="算法名称" prop="skuName">
              <el-input v-model="algoForm.skuName" placeholder="请输入" @input="inputValueChange" type="text" maxlength="32"
                show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="特征库层" prop="layer">
              <el-select clearable="" v-model="algoForm.layer" filterable placeholder="请选择层">
                <el-option v-for="item in layerList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="V4算法主图" prop="algMainImg">
              <input type="file" id="algMainImg" @change="handFileChange" />
              <img style="width: 100px" :src="mainImgUrl" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前小图总数:">
              <span>{{ this.minImgListSum }}</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="delMinImgList">一键清空小图</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="小图组" prop="algMinImgList">
              <el-upload class="upload-demo" ref="upload" action="/" :on-change="changeFile" :on-preview="handlePreview"
                :on-remove="handleRemove" :file-list="fileList" multiple :auto-upload="false" list-type="picture-card">
                <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelCreate">取 消</el-button>
        <el-button type="primary" @click="submitCreate">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!-- 查看设置阈值 弹出框 -->
    <el-dialog title="阈值设置" v-loading="setLoading" element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)" :visible.sync="thresholdDialogOpen" @close="cancelSet" width="800px"
      append-to-body>
      <el-form :model="thresholdForm" label-width="170px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="检测框的置信度" prop="boxThreshold">
              <el-input v-model="thresholdForm.boxThreshold" placeholder="请输入" @input="inputValueChange" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="相似度最高SKU的相似度" prop="featureThreshold">
              <el-input v-model="thresholdForm.featureThreshold" placeholder="请输入" @input="inputValueChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSet">取 消</el-button>
        <el-button type="primary" @click="submitSet">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 重启算法服务 弹出框 -->
    <el-dialog title="重启服务参数" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
      :visible.sync="restartDialogOpen" @close="cancelRestart" width="650px" append-to-body>
      <el-form label-width="150px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="featurenetName：">
              <el-input v-model="restartForm.featurenetName" placeholder="请输入featurenetName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="重新提取特征值：">
              <el-select v-model="restartForm.regetfeats" placeholder="请选择">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="yolonetName：">
              <el-input v-model="restartForm.yolonetName" placeholder="请输入yolonetName" />
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRestart">取 消</el-button>
        <el-button type="primary" @click="restartV4">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 同步算法 弹出框 -->
    <el-dialog :title="'算法同步:' + this.targetEnv" element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)" :visible.sync="targetEnvSkuDialogOpen" @close="cancelSync"
      width="1000px" append-to-body>
      <!-- 表格数据展示 -->
      <el-table v-loading="targetSkuLoading" :data="targetSkuList" style="width: 100%;margin-top: 1%;" empty-text="--"
        @selection-change="handleTargetSkuSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="算法Id" align="center" prop="skuId" />
        <el-table-column label="算法名称" align="center" prop="skuName" />
        <el-table-column label="特征库层" align="center" prop="layer">
          <template slot-scope="scope">
            <div>{{ scope.row.layer === 1 ? '顶层' : scope.row.layer === 2 ? '中间层' : '底层' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="主图" align="center" prop="packageUrl">
          <template slot-scope="scope">
            <div>
              <el-popover trigger="hover" placement="bottom" width="400">
                <img slot="reference" :src="scope.row.packageUrl" style="width: 20px;height: 20px;"
                  v-if="scope.row.packageUrl" />
                <img :src="scope.row.packageUrl" style="width: 300px" v-if="scope.row.packageUrl" />
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="当前小图情况" align="center" prop="imageCount">
          <template slot-scope="scope">
            <el-button size="mini" style="font-size: 22px;" type="text">
              {{ scope.row.imageCount }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="targetSkuPagn.total > 0" :total="targetSkuPagn.total" :page.sync="targetSkuPagn.pageNum"
        :limit.sync="targetSkuPagn.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500, 1000, 2000, 3000]"
        @pagination="getAlgoData" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSync">取 消</el-button>
        <el-button type="primary" @click="startSync">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看算法同步结果 弹出框 -->
    <!-- <el-dialog
      title="查看算法同步结果"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :visible.sync="getSyncResultDialog"
      @close="cancelGetSyncResultDialog"
      width="500px"
      append-to-body
    >
      <el-form
        :model="getSyncResultForm"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="requestId" prop="requestId">
              <el-input v-model="getSyncResultForm.requestId" placeholder="请输入" @input="inputValueChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelGetSyncResultDialog">取 消</el-button>
        <el-button type="primary" @click="getSyncResult">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { setInitImg } from '@/utils/url-transfer-file'
import { getToken } from '@/utils/auth'
import { getThresholdValueV4, setThresholdValueV4, algRegisterV4, getArithmeticDetail, getAlgListV4, delAlgoV4, v4Restart, getV4RestartResult, algModifyV4 } from '@/api/arithmetic/arithmetic';
export default {
  name: "algorithm-manage",
  data() {
    return {
      getSyncResultDialog: false, // 获取算法同步结果弹框
      // 获取算法同步结果表单
      getSyncResultForm: {
        requestId: ''
      },
      targetSkuLoading: '', // 目标环境sku列表加载
      targetSkuPagn: {
        total: 0,
        pageSize: 20,
        pageNum: 1,
      },
      targetEnvSkuDialogOpen: false, // 目标环境sku列表弹框
      targetSkuList: [], // 目标环境sku列表
      syncList: [], // 需要同步的算法列表
      targetEnv: '', // 算法同步目标环境
      selectData: [],
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/firmware/upload", // 上传文件服务器地址
      headers: {
        'User-Token': getToken(),
      },
      fileList: [],
      urlFile: '',
      layerList: [
        {
          name: '顶层库',
          id: 1
        },
        {
          name: '中间层库',
          id: 2
        },
        {
          name: '底层库',
          id: 3
        },
      ],
      options: [
        {
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ],
      dialogImageUrl: '',//放大图片的url
      dialogVisible: false,//点击放大
      setLoading: false,
      thresholdDialogOpen: false,
      restartDialogOpen: false,
      thresholdForm: {
        boxThreshold: '',//检测框的置信度
        featureThreshold: '',//相似度最高SKU的相似度
      },
      restartForm: {
        featurenetName: "",//特征值文件
        regetfeats: false,//是否重新提取特征值
        // soUrl:"",//so库文件
        yolonetName: "",//模型文件
      },
      // canUploadMinImg:true,//是否能上传小图
      buttonShow: true,//是否显示“确定”“取消”按钮
      minImgListSum: 0,//小图组总数
      topImgListSum: 0,//顶层小图总数
      midImgListSum: 0,//顶层小图总数
      botImgListSum: 0,//顶层小图总数
      dialogFull: false,//是否全屏展示dialog，用于解决小图组图片过多与用户交互困难问题
      uploadLoading: false,//提交表单时的用户交互
      changeMark: 0,//作用于强制刷新页面，后台返回小图组数量后可删除
      fileList: [],//小图组上传列表
      topFileList: [],//顶层小图上传列表
      midFileList: [],//中间层小图上传列表
      botFileList: [],//底层小图上传列表
      chooseSkuIdList: [],//选中行skuId列表
      mainImgUrl: '',//主图url
      loading: false,//用于table表格加载
      //表单字段
      algoForm: {
        imageCount: '',
        name: '',
        algMainImg: '',
        layer: '',
        algMinImgList: [],
        pics: []
      },
      //表单校验
      algoFormRules: {
        name: [{ required: true, message: '请填写算法名称', trigger: 'blur' }],
        algMainImg: [{ required: true, message: '请上传主图', trigger: 'blur' }],
      },
      //检索表单
      queryParams: {
        skuName: '',
        layer: '',
        skuId: ''
      },
      alogData: [],//表格数据
      alogPagn: {
        total: 0,
        pageSize: 20,
        pageNum: 1,
      },
      dialogTitle: '新增算法',
      dialogOpen: false,
      showSearch:true,
    }
  },
  created() {
    /** 获取V4算法阈值 */
    // getThresholdValueV4().then((res) =>{
    //   if(res.success){
    //     this.thresholdForm=res.data
    //   }
    // }).catch((err) => {
    //   this.$message.error('阈值获取失败,原因：', err.message)
    // })
    this.getAlgoData()
  },
  methods: {
    //小图组清空
    delMinImgList() {
      this.algoForm.algMinImgList = []
      this.minImgListSum = 0
      this.$refs.upload.clearFiles();
      if (this.dialogTitle == "小图情况") {
        this.algoForm.files = []
      }
    },
    //获取重启结果
    getRestartResult() {
      getV4RestartResult()
        .then((res) => {
          if (res.code === 0) {
            this.$message.success("重启成功")
          }
        }).catch((err) => {
          this.$alert(err.message, '提示', {
            confirmButtonText: '确定',
          });
        })

    },
    // /** 打开弹框-算法同步结果 */
    // syncResult(){
    //   this.getSyncResultDialog = true
    // },
    // /** 获取算法同步结果 */
    // getSyncResult(){
    //   if(this.getSyncResultForm.requestId == ''){
    //     this.$message.error("请输入requestId!")
    //     return
    //   }
    //   let params={
    //     requestId:this.getSyncResultForm.requestId+''
    //   }
    //   getAlgSyncResult(params).then((res) =>{
    //     console.log("同步结果查询成功",res)

    //     if(res.code === 0){
    //       let fv
    //       if(res.data.failList !== null){
    //         fv = res.data.failList.map((v) => v.skuId+'-'+v.skuName+'-'+v.status+'-'+v.message).join(',')
    //       }

    //       let text = `<p>总数: ${res.data.skuCount || '0'}</p>
    //       <p>成功: ${res.data.successCount || '0'}</p>
    //       <p>失败：${res.data.failCount || '0'}</p>
    //       <p>失败算法列表: ${fv || '无'}</p>`
    //       this.$confirm(text, '算法同步结果('+ +res.data.status ? '完成' : '未完成'+')', {
    //         confirmButtonText: '确定',
    //         dangerouslyUseHTMLString: true,
    //         showCancelButton: false,
    //         type: 'warning',
    //       })
    //       if(res.data.failCount > 0){
    //         this.$confirm(text, '算法同步结果('+ +res.data.status ? '完成' : '未完成'+')', {
    //           confirmButtonText: '确定',
    //           dangerouslyUseHTMLString: true,
    //           showCancelButton: false,
    //           type: 'warning',
    //         })
    //       }else{
    //         this.$confirm(text, '算法同步结果('+ +res.data.status ? '完成' : '未完成'+')', {
    //           confirmButtonText: '确定',
    //           dangerouslyUseHTMLString: true,
    //           showCancelButton: false,
    //           type: 'success',
    //         })
    //       }

    //     }
    //   }).catch((err) =>{
    //      this.$message.success("结果查询失败，原因：",err.message)
    //   })
    // },

    /** 点击算法同步按钮 */
    // syncV4(){
    //   console.log(process.env.VUE_APP_BASE_API)
    //   if( process.env.VUE_APP_BASE_API == '/dev-api'){
    //     console.log("当前为测试环境",process.env.VUE_APP_BASE_API)
    //     this.targetEnv = 'PROD'
    //   }else{
    //     console.log("当前为正式环境",process.env.VUE_APP_BASE_API)
    //     this.targetEnv = 'DEV'
    //   }
    //   //获取另一个环境的算法sku列表
    //   this.getOtherEnvALGList()
    //   //打开弹框
    //   this.targetEnvSkuDialogOpen = true
    // },
    //点击重启按钮
    PTRestartV4() {
      this.restartDialogOpen = true
    },
    /** 开始同步算法 */
    startSync() {
      if (this.syncList.length === 0) {
        this.$message.warning("请选择算法进行同步")
        return
      }
      startSyncAlg(this.syncList).then((res) => {
        if (res.code === 0) {
          this.$message.success("同步中……可点击查询按钮查询结果：" + res.data)
        } else {
          this.$message.success("同步失败，原因：" + res.data)
        }
      }).catch((err) => {
        this.$message.success("同步失败，原因：", err.message)
      })
    },
    //重启v4算法服务
    restartV4() {
      // 提示，确定重启？
      console.log("开始重启服务……")
      const params = {
        ...this.restartForm
      }
      v4Restart(params).then((res) => {
        if (res.code === 0) {
          this.restartDialogOpen = false
          this.$message.success("开始成功，点击`查看重启结果`按钮查询进度")
        }
      }).catch((err) => {
        this.$alert('失败:' + err.message, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.restartDialogOpen = false
          }
        });
      })

    },
    /** 根据环境获取算法SKU列表 */
    // getOtherEnvALGList(){
    //   const params = {
    //     pageIndex: this.targetSkuPagn.pageNum - 1,
    //     pageSize: this.targetSkuPagn.pageSize,
    //     // skuName:this.queryParams.skuName || '',
    //     // layer:this.queryParams.layer || 0,
    //     // skuId:this.queryParams.skuId
    //     // pageIndex: 0,
    //     // pageSize: 20,
    //     env:this.targetEnv,
    //   }
    //   this.targetSkuLoading = true
    //   getAlgListV4(params)
    //     .then((res) => {
    //       console.log("获取另一个环境的数据",res)
    //       if(res.code === 0 ){
    //         this.targetSkuList = res.data.data
    //         const { data, pageIndex, totalCount } = res.data || {}
    //         this.targetSkuList = data
    //         this.targetSkuPagn = {
    //           pageNum:pageIndex+1,
    //           total: totalCount,
    //           pageSize: this.targetSkuPagn.pageSize
    //         }
    //       }


    //       this.loading = false
    //       const { data, pageIndex, totalCount } = res.data || {}
    //       this.alogData = data
    //       this.alogPagn = {
    //         pageNum:pageIndex+1,
    //         total: totalCount,
    //         pageSize: this.alogPagn.pageSize
    //       }
    //       this.alogData.forEach((item) =>{
    //         const param = {
    //           skuId:item.id
    //         }
    //         getAlgImgListV4(param).then((res) => { 
    //           if(res.data){
    //             item.imgList=res.data
    //           }
    //         })
    //       })
    //       console.log("alogData:",this.alogData)
    //       })
    //       .catch((err) =>{
    //         console.log("小图列表获取失败",err.message)
    //       })
    //       .finally(() =>{
    //         this.targetSkuLoading = false
    //       })
    // },
    submitSet() {
      const params = {
        boxThreshold: this.thresholdForm.boxThreshold,
        featureThreshold: this.thresholdForm.featureThreshold
      }
      setThresholdValueV4(params).then((res) => {
        if (res.success) {
          this.$message.success('阈值设置成功')
          this.thresholdDialogOpen = false
          getThresholdValueV4().then((res) => {
            if (res.success) {
              this.thresholdForm = res.data
            }
          }).catch((err) => {
            this.$message.error('阈值获取失败,原因：', err.message)
          })
        }
      })

    },
    /** 获取阈值 */
    getThreshold() {
      getThresholdValueV4().then((res) => {
        if (res.code === 0) {
          this.thresholdForm = res.data
          this.thresholdDialogOpen = true
        }
      }).catch((err) => {
        this.$message.error('阈值获取失败,原因：', err.message)
      })

    },
    /** 关闭算法同步结果弹框 */
    cancelGetSyncResultDialog() {
      this.getSyncResultDialog = false
    },
    /** 关闭算法同步弹框 */
    cancelSync() {
      this.targetEnvSkuDialogOpen = false
      //清空选中的同步sku列表
      this.syncList = []
    },
    cancelRestart() {
      this.restartDialogOpen = false
      this.restartForm = {
        featurenetUrl: '',
        regetfeats: false,
        soUrl: '',
        yolonetUrl: '',
      }
    },
    cancelSet() {
      this.thresholdDialogOpen = false
    },
    //批量删除
    handleBatchDel() {
      if (this.chooseSkuIdList.length === 0) {
        this.$confirm(`请至少勾选一条算法！`, '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
        })
      } else {
        this.$confirm(`是否删除这${this.chooseSkuIdList.length}条数据？`, '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
        })
          .then(() => {
            //看后台给单条还是多条删除接口
            for (var i = 0; i < this.chooseSkuIdList.length; i++) {
              this.deleteRowBatch(this.chooseSkuIdList[i])
            }
            //   console.log('## row ==> ', this.chooseSkuIdList)
            //   const param = {
            //     skuIds: window.localStorage.getItem(this.chooseSkuIdList)
            //   }
            //   delAlgoV4Batch(param).then((res) => {
            //     if (res.code === 0) {
            //       this.$message.success('删除成功')
            //       this.getAlgoData()
            //     }
            //   }).catch((err) => {
            //     this.$message.error('删除失败')
            //   })
          })
          .catch(() => { })
      }

    },
    //行选中
    handleSelectionChange(chooseRowList) {
      this.chooseSkuIdList = []
      if (chooseRowList.length > 0) {
        for (var i = 0; i < chooseRowList.length; i++) {
          if (this.chooseSkuIdList.indexOf(chooseRowList[i].skuId) === -1) {
            this.chooseSkuIdList.push(chooseRowList[i].id)
          }
        }
      }
    },
    /** 需要同步的算法行选中 */
    handleTargetSkuSelectionChange(chooseRowList) {
      this.syncList = []
      if (chooseRowList.length > 0) {
        for (var i = 0; i < chooseRowList.length; i++) {
          if (this.syncList.indexOf(chooseRowList[i].skuId) === -1) {
            this.syncList.push(chooseRowList[i].skuId)
          }
        }
      }
    },
    //该方法解决输入不显示问题
    inputValueChange() {
      //输入框强制刷新
      this.$forceUpdate()
    },
    //点击删除-跳出交互界面
    handleDel(row) {
      this.$confirm('是否删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
        .then(() => {
          this.deleteRow(row)

        })
        .catch(() => { })
    },
    handleEnter(row, e) {
      // console.log("===>handleEnter")
    },
    handleOut() {
      // console.log("===>handleOut")
    },
    popupMouse(flag) {
      this.pt = flag;
    },
    //用户假批量
    deleteRowBatch(row) {
      const param = {
        skuId: row
      }
      delAlgoV4(param).then((res) => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.getAlgoData()
        }
      }).catch((err) => {
        this.$message.error('删除失败')
      })
    },
    //删除方法
    deleteRow(row) {
      const param = {
        skuId: row.id
      }
      delAlgoV4(param).then((res) => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.getAlgoData()
        }else if(res.code === 1){
          this.$message.warning('删除失败,原因：'+res.message)
        }
      }).catch((err) => {
        this.$message.error("删除失败",err.message)
      })
    },
    //检索
    queryByForm() {
      this.getAlgoData()
    },
    handleAdd() {
      //表单数据初始化
      this.algoForm.skuName = ''
      if (document.getElementById('algMainImg')) {
        document.getElementById('algMainImg').value = '';
      }
      this.algoForm.algMinImgList = []
      this.mainImgUrl = ''
      this.fileList = []
      this.minImgListSum = 0
      this.dialogTitle = "新增sku算法"
      this.dialogOpen = true
    },
    //点击小图数量
    handleEdit(row) {
      this.dialogOpen = true
      this.dialogTitle = "小图情况"
      //todo 调用详情接口
      const param = {
        skuId: row.id
      }
      getArithmeticDetail(param).then((res) => {
        if (res.code === 0 && res.data) {
          // this.algoForm = res.data
          this.algoForm.skuId = row.id
          this.algoForm.skuName = res.data.name
          this.algoForm.layer = res.data.layer
          this.minImgListSum = res.data.imageCount
          this.mainImgUrl = res.data.packageUrl
          this.algoForm.algMinImgList = res.data.pics
          this.fileList = res.data.pics.map(item => {
            return {
              name: item,
              url: item
            }
          });
          var index = res.data.packageUrl.lastIndexOf('/')

          this.algoForm.algMainImg = res.data.packageUrl.substring(index + 1, res.data.packageUrl.length)
          //主图url转file
          setInitImg(this.algoForm.packageFile, (file) => {
            this.algoForm.packageFile = file
          })
          //用于存放小图组files
          this.algoForm.files = []
          // //小图组url转file
          this.algoForm.algMinImgList.forEach((item) => {
            setInitImg(item, (file) => {
              this.algoForm.files.push(file)
            })
          })
        }

      })
    },
    //获取表格数据
    getAlgoData() {
      console.log(this.alogPagn)
      const params = {
        pageIndex: this.alogPagn.pageNum -1 ,
        pageSize: this.alogPagn.pageSize,
        skuName: this.queryParams.skuName || '',
        layer: this.queryParams.layer || "",
        skuId: this.queryParams.skuId
      }
      this.loading = true
      getAlgListV4(params)
        .then((res) => {
          console.log(res.message)
          if(res.code === 1){
            this.$message.error("2222小图列表获取失败,原因："+res.message)
          }else{
            this.loading = false
            const { data, pageIndex, totalCount } = res.data || {}
            this.alogData = data
            this.alogPagn = {
              pageNum: pageIndex + 1,
              total: totalCount,
              pageSize: this.alogPagn.pageSize
            }
          }
        })
        .finally(() => {

        })
    },
    cancelCreate() {
      this.dialogOpen = false
      this.algoForm = {}
    },
    submitCreate() {
      this.$refs.algoForm.validate((valid) => {
        if (!valid) {
          return
        }
        if (this.algoForm.skuName == '') {
          this.$confirm('请输入sku名称', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
          })
        }

        if (this.algoForm.algMainImg == '') {
          this.$confirm('请上传主图', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
          })
        }
        const form = this.algoForm
        let str = ''
        const formData = new FormData()
        if (this.dialogTitle == '小图情况') {
          Object.keys(form).forEach((key) => {
            //拼接参数到url
            if (key == 'skuId') {
              str += `&${key}=${form[key]}`
            }
          })
          formData.append('packageFile', form.algMainImg)
          for (var i = 0; i < form.files.length; i++) {
            formData.append("files", form.files[i])
          }
          // formData.append("files",form.files)
          const params = {
            url: str,
            file: formData
          }
          this.uploadLoading = true
          this.$notify({
            title: '提示',
            message: '图片上传中,请稍后…',
            offset: 700,
            duration: 0
          });
          this.dialogFull = true
          algModifyV4(params).then((res) => {
            this.$message.success('修改成功')
            this.$notify.closeAll();//去掉交互框
            this.dialogOpen = false
            this.getAlgoData()
          })
            .catch((err) => {
              this.$message.error(err)
            })
            .finally(() => {
              this.dialogFull = false
              this.uploadLoading = false
            })

        } else {
          Object.keys(form).forEach((key) => {
            //拼接参数到url
            if (key !== 'algMainImg' && key !== 'algMinImgList' && key !== 'packageFile') {
              str += `&${key}=${form[key]}`
            }
          })
          formData.append('packageFile', form.algMainImg)
          for (var i = 0; i < form.algMinImgList.length; i++) {
            formData.append("files", form.algMinImgList[i])
          }
          const params = {
            url: str,
            file: formData
          }
          this.uploadLoading = true
          this.$notify({
            title: '提示',
            message: '图片上传中,请稍后…',
            offset: 700,
            duration: 0
          });
          this.dialogFull = true
          algRegisterV4(params).then((res) => {
            this.$message.success('新增成功')
            this.$notify.closeAll();//去掉交互框
            this.dialogOpen = false
            this.getAlgoData()
          })
            .catch((err) => {
              this.$message.error(err)
            })
            .finally(() => {
              this.dialogFull = false
              this.uploadLoading = false
            })
        }

      })
    },
    targetAloGpagination() {
      this.getOtherEnvALGList()
    },
    aloGpagination() {
      this.getAlgoData()
    },
    cancel() {
      this.dialogOpen = false
      this.algoForm = {}
    },
    handFileChange(e) {
      let fileData = e.target.files[0] //这是我们上传的文件
      this.algoForm.algMainImg = fileData
      this.algoForm.packageFile = fileData
      let url = URL.createObjectURL(fileData)
      this.mainImgUrl = url
    },
    changeFile(file, fileList) {
      let fileData = file.raw
      if (this.dialogTitle == '小图情况') {
        this.algoForm.files.push(fileData)
        this.minImgListSum++
      } else {
        this.algoForm.algMinImgList.push(fileData)
        this.minImgListSum++
      }
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      if (this.dialogTitle == '小图情况') {
        //不存在则是-1,删除url
        var index = this.algoForm.algMinImgList.indexOf(file.url)
        let fileName = file.name.substring(file.name.lastIndexOf("/") + 1);
        let delFile = this.algoForm.files.find((d) => d.name == fileName)
        //不存在则是-1,删除file
        let mark = this.algoForm.files.indexOf(delFile);
        if (index !== -1) {
          this.algoForm.algMinImgList.splice(index, 1)
          this.minImgListSum--
          if (mark !== -1) {
            this.algoForm.files.splice(mark, 1)
          }
        }
      } else {
        //不存在则是-1
        var index = this.algoForm.algMinImgList.indexOf(file.raw)
        if (index !== -1) {
          this.algoForm.algMinImgList.splice(index, 1)
          this.minImgListSum--
        }
      }


    },

  },
}
</script>

<style lang="scss" scoped></style>